<template>
  <div class="news-activity">
    <CustomSwiper :data="activityBanner" controls @slide-click="handleBanner" />
    <!-- <Banner class="h-[100%] news-activity-banner" :slides="activityBanner" @slide-click="handleBanner" /> -->
    <div class="news-activity-content">
      <div class="news-activity-content-header flex-wrap">
        <div class="news-activity-content-header-title">
          {{ activityTile }}
        </div>
        <ClientOnly>
          <d-input v-model="searchText" class="flex-1 min-w-[100px]" :maxlength="100" :placeholder="$t('course.searchPlaceholder')" @keypress.enter="search">
            <template #prefix>
              <GIcon name="gt-search" />
            </template>
          </d-input>
        </ClientOnly>
      </div>
      <template v-if="activeTab === 'activity-view'">
        <div class="news-activity-content-type">
          <ActivityTypeSelect v-model="filterParams.type" :types="activityTypeList" @change="handleChangeType" />
        </div>
        <ul v-if="showList.length" class="news-activity-content-list">
          <template v-for="(item, index) in showList">
            <li v-if="showIndex > index" :key="index">
              <ActivityCard :activity="item" />
            </li>
          </template>
        </ul>
        <EmptyData v-else-if="showList.length === 0" :hide-icon="false" class="h-full flex-1" />
        <div class="flex justify-center mt-[32px]" v-if="showIndex < showList.length">
          <div class="news-activity-content-list-more" @click="handleMore">
            {{ $t('common.more') }}
            <GIcon name="gt-line-down" />
          </div>
        </div>
      </template>
      <template v-if="activeTab === 'calendar-view'">
        <ActivityDetails v-if="!isPhone() && currentDateData" :data="currentDateData" @handleBack="handleBack">
          <template #checkbox>
            <ActivityTypeSelect v-model="filterParams.type" :types="activityTypeList" @change="handleChangeType" />
          </template>
        </ActivityDetails>
        <EmptyData 
          v-if="
            !isPhone() &&
            currentDateData &&
            ((currentDateData.data.length &&
            !currentDateData.data.find((item: { show: boolean; }) => item.show)) || !currentDateData?.data.length )
          "
          :hide-icon="false"
          class="h-full flex-1"
        />
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useTimeFormat } from '@/composables/hooks/useTimeFormat'
import allData from '@/pages/Data/course.json'
import { useI18n } from 'vue-i18n';
import ActivityCard from './components/activityCard.vue'
import ActivityTypeSelect from './components/activityTypeSelect.vue'
import ActivityDetails from '../Activity/components/activityDetails.vue'
import CustomSwiper from '@/components/CustomSwiper/index.vue'
import isPhone from '@/utils/isPhone';
import { keepAliveComponentName } from '@/constant';
const { t } = useI18n()
const { formatTime } = useTimeFormat();
// 获取cookie里参数
const lan = useCookie('lang').value || 'zh';

const currentDateData = ref(null);

let data = allData[lan] || allData.zh;

const calendarRef = ref(null);
// 对取到的数据做处理（排序，状态）
data.sort((a: { updateTime: string; }, b: { updateTime: string; }) => Number(new Date(b.updateTime)) - Number(new Date(a.updateTime)));
const activityList = data.map((item) => {
  return {
    ...item,
    // show: true,
    // status: currentTime < startTimes ? 0 : currentTime > endTimes ? 2 : 1,
  }
})

// 获取isBanner为1的活动作为横幅内容，如果不足4个则补充其他活动
const getBannerActivities = () => {
  // isBanner为1的活动
  const bannerActivities = activityList.filter((item: any) => item.isBanner).slice(0, 4);
  // 如果不足4个，按时间顺序补充
  const otherActivities = activityList.filter((item: any) => !item.isBanner);
  const neededCount = 4 - bannerActivities.length;
  return [...bannerActivities, ...otherActivities.slice(0, neededCount)];
}
const activityBanner = ref(getBannerActivities())

// 获取活动类型，liveBroadcastType
const activityTypeList = ref(activityList
  .map((item: any) => item.type)
  .filter((item: any, index: number, self: any) => item && self.indexOf(item) === index)
)
const showIndex = ref(8)
const showList = ref(activityList)
const filterParams = ref({
  dateTime: null,
  type: [...activityTypeList.value]
})

const searchText = ref('')
const activeTab = ref('activity-view')
const activityTile = computed(() => {
  return t('course.allCourse')
})

function search() {
  navigateTo({
    name: 'search',
    query: {
      search: searchText.value,
      tab: 'course'
    }
  })
}

const handleBack = () => {
  currentDateData.value = null
}

function handleBanner({ slide, index }: { slide: any, index: number }) {
  window.open(`/course/${slide.id}`, '_blank');
}

function handleMore() {
  showIndex.value += 8
}

// 处理过滤
const handleFilter = () => {
  let showData = activityList;
  showData = showData.filter((item: { type: string; }) => !item.type || filterParams.value.type.includes(item.type))
  if (filterParams.value.dateTime) {
    showData = showData.filter((item: { startTime: string; endTime: string; }) => {
      const selectedMonth = formatTime(filterParams.value.dateTime, 'YYYY-MM');
      const startMonth = formatTime(item.startTime, 'YYYY-MM');
      const endMonth = formatTime(item.endTime, 'YYYY-MM');
      // 检查选择的月份是否在活动的开始月份和结束月份之间（包含边界）
      return selectedMonth >= startMonth && selectedMonth <= endMonth;
    })
  }
  showList.value = showData
}

// 过滤活动类型
const handleChangeType = (types: string[]) => {
  showIndex.value = 8
  filterParams.value.type = types
  handleFilter();
  if (currentDateData.value) {
    currentDateData.value.data?.forEach((item: { type: string; }) => {
      item.show = !item.type || types.includes(item.type);
    })
  }
  if (calendarRef.value) {
    calendarRef.value.changeSelectDate(types)
  }
}

defineOptions({
  name: keepAliveComponentName.Activity
})

useSeoMeta({
  charset: 'utf-8',
  title: () => t('course.tdk.title'),
  ogTitle: () => t('course.tdk.title'),
  description: () => t('course.tdk.desc'),
  ogDescription: () => t('course.tdk.desc'),
  keywords: () => t('course.tdk.keyword'),
  ogKeywords: () => t('course.tdk.keyword'),
})
</script>

<style lang="scss" scoped>
.news-activity {
  color: #3B3E55;

  &-bg {
    background: url('@/assets/img/activity-bg.png') no-repeat;
    background-size: cover;
  }

  &-banner {
    padding: 0 0 32px;
  }

  &-content {
    margin: auto;
    margin-top: 16px;
    max-width: 1200px;

    &-header {
      display: flex;
      align-items: center;
      gap: 32px;
      padding-bottom: 16px;

      &-title {
        background: linear-gradient(90deg, #2951E0 0%, #8A25D9 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: #0000;
        font-weight: 600;
        font-size: 20px;
      }
    }

    &-type {
      height: 32px;
      display: flex;
      align-items: center;
    }

    &-list {
      display: grid;
      grid-template-columns: repeat(4, calc(25% - 12px));
      gap: 16px;
      margin-top: 16px;

      &-item {
        display: flex;
        align-items: center;
        border-radius: 4px;
        cursor: pointer;
        padding-right: 16px;
        gap: 16px;

        &:hover {
          background: #F9F9FB;
        }

        img {
          border-radius: 4px;
          object-fit: cover;
        }

        &-time {
          padding: 14px 16px;
        }

        &-date {
          font-size: 16px;
          font-weight: 600;
          color: #000;
          font-size: 20px;
        }

        &-title {
          font-weight: 600;
          font-size: 16px;
        }

        &-img {
          border-left: 1px solid #F1F1F8;
        }

        &.g-link:hover {
          color: inherit;
        }
      }

      &-more {
        cursor: pointer;

        &:hover {
          color: #2951E0;

          svg {
            color: #2951E0 !important;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 1204px) {
  .news-activity-content {
    &-list {
      grid-template-columns: repeat(2, calc(50% - 8px));
    }
  }
  :deep(.activity-card__image) {
    height: 150px;
  }
  :deep(.carousel-viewport) {
    height: 180px!important;
  }
}

@media screen and (max-width: 768px) {
  .news-activity-content{
    &-list {
      grid-template-columns: repeat(1, 100%);
    }
    :deep(.activity-card__image) {
      height: 190px;
    }
  }
  .news-activity-banner {
    padding: 0 0 16px;
  }
  .news-activity-content-header{
    gap: 16px;
    &-date {
      width: 145px;
    }
  }
  :deep(.carousel-viewport) {
    height: 140px!important;
  }
}
</style>
